<template>
  <view class="login-page">
    <!-- 顶部装饰背景 -->
    <view class="header-bg">
      <view class="bg-decoration"></view>
    </view>
    
    <view class="login-container">
      <!-- Logo和标题 -->
      <view class="logo-section">
        <image src="/static/logo.png" class="logo" mode="aspectFit" />
        <text class="app-name">MVR设备租赁平台</text>
        <text class="app-slogan">专业工业设备 按需租赁</text>
      </view>

      <!-- 身份选择 -->
      <view class="role-tabs">
        <view 
          class="role-tab"
          :class="{ active: selectedRole === 'renter' }"
          @click="selectRole('renter')"
        >
          <u-icon name="account-fill" size="18" color="#fff"></u-icon>
          <text class="role-text">我是租户</text>
        </view>
        <view 
          class="role-tab"
          :class="{ active: selectedRole === 'owner' }"
          @click="selectRole('owner')"
        >
          <u-icon name="plus-people-fill" size="18" color="#fff"></u-icon>
          <text class="role-text">我是出租方</text>
        </view>
      </view>

      <!-- 短信验证登录表单 -->
      <u-form :model="form" ref="uForm" :rules="rules" :error-type="['toast']">
        <!-- 手机号输入 -->
        <u-form-item prop="phone" class="form-item">
          <u-input 
            v-model="form.phone" 
            placeholder="请输入手机号" 
            type="number" 
            maxlength="11" 
            clearable
            prefix-icon="phone"
            :custom-style="inputStyle"
          />
        </u-form-item>

        <!-- 验证码输入 -->
        <u-form-item prop="code" class="form-item">
          <u-input 
            v-model="form.code" 
            placeholder="请输入验证码" 
            type="number" 
            maxlength="4" 
            clearable
            prefix-icon="lock"
            :custom-style="inputStyle"
          >
            <template #suffix>
              <u-button 
                :disabled="codeButtonDisabled"
                @click="sendCode"
                :loading="sendingCode"
                type="primary"
                size="mini"
                :custom-style="{ 
                  height: '60rpx', 
                  fontSize: '24rpx',
                  backgroundColor: codeButtonDisabled ? '#f0f0f0' : '#4A90E2'
                }"
              >
                {{ getCodeButtonText() }}
              </u-button>
            </template>
          </u-input>
        </u-form-item>
      </u-form>

      <!-- 短信验证登录按钮 -->
      <u-button 
        type="primary"
        :loading="loading"
        @click="handleSmsLogin"
        :custom-style="buttonStyle"
        class="submit-btn"
      >
        验证码登录
      </u-button>

      <!-- 说明文字 -->
      <view class="login-tip">
        <text class="tip-text">首次登录将自动注册账号</text>
      </view>

      <!-- 协议和隐私 -->
      <view class="agreement">
        <text class="agreement-text">
          登录即表示您已阅读并同意
          <text class="link-text" @click="viewAgreement('user')">《用户协议》</text>
          和
          <text class="link-text" @click="viewAgreement('privacy')">《隐私政策》</text>
        </text>
      </view>
    </view>
  </view>
</template>

<script>
import apiService from '@/api/index.js'
import { handleLoginSuccess } from '@/utils/auth.js'

export default {
  data() {
    return {
      selectedRole: 'renter', // renter: 租户, owner: 出租方
      loading: false,
      sendingCode: false,
      codeButtonDisabled: false,
      countdown: 0,

      form: {
        phone: '',
        code: ''
      },

      rules: {
        phone: [
          {
            required: true,
            message: '请输入手机号',
            trigger: ['blur', 'change']
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号格式不正确',
            trigger: ['blur', 'change']
          }
        ],
        code: [
          {
            required: true,
            message: '请输入验证码',
            trigger: ['blur', 'change']
          },
          {
            pattern: /^\d{4}$/,
            message: '验证码必须为4位数字',
            trigger: ['blur', 'change']
          }
        ]
      },

      inputStyle: {
        backgroundColor: '#f8f9fa',
        border: 'none',
        borderRadius: '12rpx',
        padding: '24rpx 20rpx'
      },

      buttonStyle: {
        backgroundColor: '#4A90E2',
        borderRadius: '12rpx',
        height: '88rpx'
      },


    }
  },

  onLoad(options) {
    // 检查是否有跳转参数
    if (options.action === 'register') {
      this.isRegister = true
    }
    if (options.role) {
      this.selectedRole = options.role
    }
  },

  methods: {
    selectRole(role) {
      this.selectedRole = role
    },

    toggleAction() {
      this.isRegister = !this.isRegister
      this.clearForm()
    },

    clearForm() {
      this.form = {
        phone: '',
        code: ''
      }
    },

    // 获取验证码按钮文字
    getCodeButtonText() {
      if (this.countdown > 0) {
        return `${this.countdown}s`
      }
      return '获取验证码'
    },

    // 发送验证码
    async sendCode() {
      console.log('🚀 开始发送验证码...')
      
      // 验证手机号
      if (!this.form.phone) {
        uni.showToast({
          title: '请输入手机号',
          icon: 'none'
        })
        return
      }

      if (!/^1[3-9]\d{9}$/.test(this.form.phone)) {
        uni.showToast({
          title: '手机号格式不正确',
          icon: 'none'
        })
        return
      }

      this.sendingCode = true
      
      try {
        console.log('📱 发送验证码到:', this.form.phone)
        const result = await apiService.sms.sendCode({
          phoneNumber: this.form.phone,
          purpose: 'login'
        })
        
        console.log('📨 短信发送结果:', result)
        
        console.log('🔍 检查响应结构:', {
          code: result.code,
          message: result.message,
          data: result.data
        })
        
        if (result.code === 200) {
          console.log('✅ 验证码发送成功')
          uni.showToast({
            title: '验证码发送成功',
            icon: 'success'
          })
          
          // 开始倒计时（60秒）
          this.startCountdown()
        } else {
          console.log('❌ 验证码发送失败:', result)
          uni.showToast({
            title: result.message || '发送失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('❌ 发送验证码异常:', error)
        uni.showToast({
          title: '发送失败，请重试',
          icon: 'none'
        })
      } finally {
        this.sendingCode = false
      }
    },

    // 开始倒计时
    startCountdown() {
      this.countdown = 60
      this.codeButtonDisabled = true
      
      const timer = setInterval(() => {
        this.countdown--
        if (this.countdown <= 0) {
          clearInterval(timer)
          this.codeButtonDisabled = false
        }
      }, 1000)
    },

    // 短信验证登录
    async handleSmsLogin() {
      console.log('🔐 开始短信登录...')
      
      if (this.loading) return

      // 表单验证
      try {
        await this.$refs.uForm.validate()
        console.log('✅ 表单验证通过')
      } catch (errors) {
        console.log('❌ 表单验证失败:', errors)
        return
      }

      this.loading = true

      try {
        console.log('📞 发送登录请求:', {
          phoneNumber: this.form.phone,
          code: this.form.code,
          selectedRole: this.selectedRole
        })
        
        const result = await apiService.auth.smsLogin({
          phoneNumber: this.form.phone,
          code: this.form.code,
          userType: this.selectedRole.toUpperCase() // 传递用户角色信息
        })

        console.log('🔑 登录响应:', result)
        console.log('🔍 检查登录响应结构:', {
          code: result.code,
          message: result.message,
          data: result.data
        })

        if (result.code === 200) {
          console.log('✅ 登录成功，保存用户信息:', result.data)
          
          // 保存登录信息
          uni.setStorageSync('token', result.data.token)
          uni.setStorageSync('refresh_token', result.data.refresh_token)
          uni.setStorageSync('user_info', result.data.user)
          uni.setStorageSync('just_logged_in', true) // 标记刚刚登录，用于优化页面加载

          uni.showToast({
            title: '登录成功',
            icon: 'success'
          })

          // 延迟跳转到原页面或首页
          setTimeout(() => {
            console.log('🚀 跳转到目标页面...')
            handleLoginSuccess()
          }, 1500)
        } else {
          console.log('❌ 登录失败:', result)
          uni.showToast({
            title: result.message || '登录失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('❌ 短信登录异常:', error)
        uni.showToast({
          title: error.message || '登录失败，请重试',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },

    async handleLogin() {
      // 根据后端API，登录时使用account字段（可以是手机号）
      const result = await apiService.auth.login({
        account: this.form.phone,
        password: this.form.password
      })

      // 登录成功处理
      uni.showToast({
        title: '登录成功',
        icon: 'success'
      })

      // 延迟跳转到首页
      setTimeout(() => {
        uni.reLaunch({
          url: '/pages/index/index'
        })
      }, 1500)
    },

    async handleRegister() {
      const registerData = {
        phone: this.form.phone,
        password: this.form.password,
        nickname: this.form.nickname || `${this.selectedRole === 'renter' ? '租户' : '出租方'}${Math.random().toString().slice(-4)}`
      }

      // 调用注册API
      const result = await apiService.auth.register(registerData)

      // 注册成功处理
      uni.showToast({
        title: '注册成功',
        icon: 'success'
      })

      // 延迟跳转到首页
      setTimeout(() => {
        uni.reLaunch({
          url: '/pages/index/index'
        })
      }, 1500)
    },

    async handleWechatLogin() {
      if (this.wechatLoading) return

      this.wechatLoading = true

      try {
        // 获取微信授权
        const loginResult = await uni.login({
          provider: 'weixin'
        })

        if (loginResult.code) {
          // 调用微信登录API
          const result = await apiService.auth.wechatLogin(loginResult.code)
          
          uni.showToast({
            title: '登录成功',
            icon: 'success'
          })

          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/index/index'
            })
          }, 1500)
        }
      } catch (error) {
        console.error('微信登录失败:', error)
        uni.showToast({
          title: error.message || '微信登录失败',
          icon: 'none'
        })
      } finally {
        this.wechatLoading = false
      }
    },

    viewAgreement(type) {
      const urls = {
        user: '/pages/agreement/user',
        privacy: '/pages/agreement/privacy'
      }
      
      uni.navigateTo({
        url: urls[type] || '/pages/agreement/user'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.login-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
}

.header-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 400rpx;
  overflow: hidden;
}

.bg-decoration {
  position: absolute;
  top: -200rpx;
  right: -200rpx;
  width: 600rpx;
  height: 600rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
}

.login-container {
  position: relative;
  z-index: 1;
  padding: calc(var(--status-bar-height) + 80rpx) 60rpx 60rpx;
}

.logo-section {
  text-align: center;
  margin-bottom: 80rpx;
}

.logo {
  width: 240rpx;
  height: 240rpx;
  margin: 0 auto 48rpx;
}

.app-name {
  display: block;
  font-size: $font-size-xl;
  font-weight: $font-weight-bold;
  color: $text-white;
  margin-bottom: 12rpx;
}

.app-slogan {
  display: block;
  font-size: $font-size-base;
  color: rgba(255, 255, 255, 0.8);
}

.role-tabs {
  display: flex;
  background: rgba(255, 255, 255, 0.15);
  border-radius: 16rpx;
  padding: 8rpx;
  margin-bottom: 40rpx;
  backdrop-filter: blur(10rpx);
}

.role-tab {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  padding: 20rpx;
  border-radius: 12rpx;
  color: rgba(255, 255, 255, 0.7);
  font-size: $font-size-base;
  transition: all 0.3s ease;

  &.active {
    background: rgba(255, 255, 255, 0.2);
    color: $text-white;
    font-weight: $font-weight-medium;
  }
}

.role-text {
  font-size: $font-size-base;
}

.form-item {
  margin-bottom: 32rpx;
  
  :deep(.u-form-item__body) {
    padding: 0;
    border-bottom: none;
  }
  
  :deep(.u-input) {
    background: rgba(255, 255, 255, 0.9);
    border-radius: 12rpx;
    border: none;
  }
}

.submit-btn, .wechat-btn {
  width: 100%;
  margin-bottom: 32rpx;
  box-shadow: 0 8rpx 24rpx rgba(74, 144, 226, 0.3);
}

.wechat-btn {
  box-shadow: 0 8rpx 24rpx rgba(7, 193, 96, 0.3);
}

.action-switch {
  text-align: center;
  margin-bottom: 40rpx;
}

.switch-text, .forgot-password {
  color: $text-white;
  font-size: $font-size-base;
  text-decoration: underline;
  margin: 0 16rpx;
}

.login-tip {
  margin-top: 20rpx;
  text-align: center;
}

.tip-text {
  font-size: $font-size-sm;
  color: rgba(255, 255, 255, 0.6);
}

.agreement {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  gap: 8rpx;
  color: rgba(255, 255, 255, 0.8);
  font-size: $font-size-sm;
  line-height: 1.5;
  margin-top: 40rpx;
}

.agreement-text {
  line-height: 1.5;
}

.link-text {
  color: #4A90E2;
  text-decoration: underline;
}

.forgot-modal {
  width: 600rpx;
  padding: 40rpx;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
}

.modal-title {
  font-size: $font-size-lg;
  font-weight: $font-weight-bold;
  color: $text-primary;
}

.modal-tip {
  color: $text-secondary;
  font-size: $font-size-base;
  line-height: 1.5;
  text-align: center;
}
</style> 